/**
 * author: sailing
 * date: 2018/11/14
 *
 */

import Config from "./Config";
import axios from "axios";
import tools from "./tools";
import eventBus from './eventBus'
export default {
	POST__(config) {
		return
		let url = Config.baseUrl + config.path;
		axios({
			method: "post",
			url: url,
			data: config.data
		});
	},
	POST(config) {
		let url = Config.baseUrl + config.path;
		console.log("post url:", url)
		eventBus.$emit('showLoading')
		fetch(url, {
			method: "POST",
			headers: {
				"Content-Type": "application/json;charset=UTF-8"
				//"Content-Type": "text/plain;charset=UTF-8"
			},
			body: JSON.stringify(config.data)
		})
			.then(function(response) {
				/*
				let data = response.json();
				if (config["callback"]) {
					config["callback"](data);
				}
				*/
				//eventBus.$on('Loading')
				console.log("response",response);
			})
			.catch(function(ex) {
				//eventBus.$on('showLoading')
				console.log("fetch error");
			});
	},
	 axiosGet(config) {
	 	var url
	 	if (window.location.href.indexOf('localhost:8080') != -1 ) {
	       url = '/api' + config.url || config.path
	     } else {
	       url = config.url || config.path
	     }    
        var _url = url + '?' + tools.jsonToStr(config.data)
        const callback = config.callback || function() {}
        const cb = config.cb || function() {}
        const errorFun = config.error || function() {}
        console.log("url:",_url)
        axios.get(_url)
            .then(function(response) {
                callback(response.data)
            })
            .then(function(res) {
                cb(res)
            })
            .catch(function(error) {
                errorFun(error)
            })
    },
    axiosPostFun(config) {

     // 打包用路径
     var _url
     var url = config.url || config.path
     if (window.location.href.indexOf('localhost:8080') != -1 ) {
       _url = '/api' + url
     } else {
       _url = url
     }
     console.log('post:', _url)
     // 本地测试用路径
     // var url = '/api' + config.url || config.path
     var data = config.data
     var callback = config.callback || function () {}
     var err = config.err || function () {}
     axios.post(_url, data)
       .then(function (res) {
         callback(res.data)
       })
       .catch(function (err) {
         console.log(err)
       })

   },
	GET(config) {
		let url = Config.baseUrl + "/";
		console.log('ss',url)
		fetch(url)
			.then(function(response) {
				return response.json();
			})
			.then(function(json) {
				if (config["callback"]) {
					config["callback"](json);
				}
			})
			.catch(function(ex) {
				console.log("parsing failed", ex);
			});
	}
};
 